<template>
  <div v-if="editOpen" style="width: 100%;">
    <t-row style="align-items: stretch" :gutter="14">
      <t-col :span="12">
<!--        <t-card class="step-card" size="small" title="外部项目">-->
          <t-table size="small" :loading="dataLoading" :selected-row-keys="selectedRowKeys"
                   @select-change="(val)=>{selectedRowKeys=val}" rowKey="id" :data="data" :columns="columns">
            <template #index="{ rowIndex }">
              {{ rowIndex + 1 }}
            </template>
            <template #efficiency="{row}">
              <t-input-adornment append="万元">
                <t-input-number :decimal-places="2"
                                @keyup="()=>{if(row.efficiency){row.efficiency=Number((row.efficiency || 0).toString().match(/^\d+(?:\.\d{0,2})?/))}}"
                                :allowInputOverLimit="false" clearable
                                v-model="row.efficiency"
                                theme="normal"
                                :min="0"></t-input-number>
              </t-input-adornment>
            </template>
            <template #investment="{row}">
              <t-input-adornment append="万元">
                <t-input-number :decimal-places="2"
                                @keyup="()=>{if(row.investment){row.investment=Number((row.investment || 0).toString().match(/^\d+(?:\.\d{0,2})?/))}}"
                                :allowInputOverLimit="false" clearable
                                v-model="row.investment"
                                theme="normal"
                                :min="0"></t-input-number>
              </t-input-adornment>
            </template>
            <template #projectName="{row}">
              <t-input clearable :status="row.projectNameStatus"
                       @change="()=>{if(row.projectName!==''){row.projectNameStatus = 'default'}}"
                       style="display: inline-block" v-model="row.projectName">
                <div slot="tips" v-if="row.projectNameStatus==='error'">不能为空</div>
              </t-input>
            </template>
            <template #useCompany="{ row }">
              <t-tree-select :status="row.useCompanyStatus" @change="(val,content)=>{row.useCompanyId=content.node.data.id;if(row.useCompany!==''){row.useCompanyStatus = 'default'}}" v-if="row.isInnerCompany==='1'"  clearable filterable
                             :treeProps="{keys: {value: 'label'}}" v-model="row.useCompany" :data="deptMenuOptions"
                             placeholder="选择单位">
                <div slot="tips" v-if="row.useCompanyStatus==='error'">不能为空</div>
                <div slot="tips" v-else>搜索不到请切换外部单位后手输</div>
                <template #label>
                  <t-switch
                    size="medium"
                    v-model="row.isInnerCompany"
                    :label="['内部', '外部']"
                    :customValue="['1', '0']"
                    @change="()=>{row.useCompany='';row.useCompanyId=null;row.useCompanyStatus='default'}"
                  ></t-switch>
                </template>
              </t-tree-select>
              <t-select
                v-else
                v-model="row.useCompany"
                creatable
                filterable
                placeholder="请输入"
                :status="row.useCompanyStatus"
                @change="(val,content)=>{row.useCompanyId = content.option?.id;if(row.useCompany!==''){row.useCompanyStatus = 'default'}}"
                :loading="useCompanyLoading"
                @search="remoteCompanyMethod"
                :options="useCompanyOptions"
                @create="createCompanyOptions"
                style="width: 390px;display: inline-block"
              >
                <div slot="tips" v-if="row.useCompanyStatus==='error'">不能为空</div>
                <div slot="tips" v-else>搜索不到请切换外部单位后手输</div>
                <template #label>
                  <t-switch
                    size="medium"
                    v-model="row.isInnerCompany"
                    :label="['内部', '外部']"
                    :customValue="['1', '0']"
                    @change="()=>{row.useCompany='';row.useCompanyId=null;row.useCompanyStatus='default'}"
                  ></t-switch>
                </template>
              </t-select>
            </template>
<!--            <template #note="{ row, rowIndex }">-->
<!--              <t-textarea :status="row.opinionStatus" @change="(val)=>{if(row.opinion!==''){row.opinionStatus = 'default'}}" :autosize="{minRows: 5}"-->
<!--                          v-model="row.opinion"  placeholder="请输入内容" >-->
<!--                <div slot="tips" v-if="row.opinionStatus==='error'">不能为空</div>-->
<!--              </t-textarea>-->
<!--            </template>-->
            <template #op="{ row, rowIndex }">
              <file-upload
                :status="row.imageStatus" v-model="row.sysAttMainVo.sysAttMainIds"
                :fileList.sync="row.sysAttMainEntities"
                :multiple="true"
                tips="">
                <t-button variant="outline">
                  <t-icon name="cloud-upload" slot="icon"/>
                  点击上传
                </t-button>
                <div slot="tips" v-if="row.imageStatus==='error'">不能为空</div>
              </file-upload>
            </template>
          </t-table>
          <div style="margin-top: 10px" class="btn-group-inline">
            <t-button @click="addData(1)">新增</t-button>
            <t-button @click="upData(1)">上移</t-button>
            <t-button @click="downData(1)">下移</t-button>
            <t-button @click="delData(1)">删除</t-button>
          </div>
<!--        </t-card>-->
      </t-col>
    </t-row>
  </div>
  <div v-else style="width: 100%;">
    <t-row style="align-items: stretch" :gutter="14">
      <t-col :span="12">
<!--        <t-card class="step-card" size="small" title="外部项目">-->
          <t-table size="small" :loading="dataLoading" rowKey="id" :data="data" :columns="columns2">
            <template #index="{ rowIndex }">
              {{ rowIndex + 1 }}
            </template>
            <template #op="{ row }">
              <div v-if="row?.sysAttMainEntities?.length>0">
                <a class="t-button-link" target="_blank" v-for="(item,index) in row.sysAttMainEntities" :href="item.fullFilePath" :key="index">
                  {{ item.name }}
                </a>
              </div>
            </template>
            <template #efficiency="{ row }">
              {{ row.efficiency }}万元
            </template>
            <template #investment="{ row }">
              {{ row.investment }}万元
            </template>
          </t-table>
<!--        </t-card>-->
      </t-col>
    </t-row>
  </div>
</template>

<script lang="jsx">
import FileUpload from "@/components/FileUpload/index.vue"

export default {
  name: "extend-project",
  components: {
    FileUpload
  },
  props: {
    value: Array,
    objId: [String, Number],
    editOpen: {
      type: Boolean,
      default: false
    },
  },
  data() {
    return {
      useCompanyLoading: false,
      useCompanyOptions: [],
      serviceOptions: [],
      projectOptions: [],
      deptMenuOptions: [],
      dataLoading: false,
      selectedRowKeys: [],
      data: [],
      columns: [
        {
          colKey: 'row-select',
          type: 'single',
          title: "选择",
          width: 64
        },
        {
          colKey: 'index',
          title: "序号",
          align: "center",
          width: 64
        },
        {
          colKey: "projectName",
          // title: "项目名称",
          align: "center",
          width: 300,
          title: (h, {colIndex}) => <div><span style="color: red;margin-right: 3px;">*</span>项目名称</div>,
        },
        {
          colKey: "useCompany",
          // title: "应用单位",
          align: "center",
          width: 400,
          title: (h, {colIndex}) => <div><span style="color: red;margin-right: 3px;">*</span>应用单位</div>,
        },
        {
          colKey: "efficiency",
          title: "产生效益",
          align: "center",
          width: 200,
        },
        {
          colKey: "investment",
          title: "投入情况",
          align: "center",
          width: 200,
        },
        // {
        //   colKey: 'note',
        //   title: "备注",
        //   align: "center",
        // },
        {
          colKey: 'op',
          title: "附件",
          align: "center",
        },
      ],
      columns2: [
        {
          colKey: 'index',
          title: "序号",
          align: "center",
          width: 64
        },
        {
          colKey: "projectName",
          title: "项目名称",
          align: "center",
        },
        {
          colKey: "useCompany",
          title: "应用单位",
          align: "center",
        },
        {
          colKey: "efficiency",
          title: "产生效益",
          align: "center",
        },
        {
          colKey: "investment",
          title: "投入情况",
          align: "center",
        },
        // {
        //   colKey: 'note',
        //   title: "备注",
        //   align: "center",
        // },
        {
          colKey: 'op',
          title: "附件",
          align: "center",
        },
      ],
    }
  },
  watch: {
    // objId: {
    //   immediate: true,
    //   handler(val) {
    //     if (val) {
    //       this.getCompanyList(val);
    //     }
    //   }
    // },
    // data: {
    //   deep: true,
    //   immediate: true,
    //   handler(val) {
    //     const newData = this.data.concat(this.data2).map((val, index) => ({...val, sort: index + 1}))
    //     this.$emit("input", newData);
    //   }
    // },
    // data2: {
    //   deep: true,
    //   immediate: true,
    //   handler(val) {
    //     const newData = this.data.concat(this.data2).map((val, index) => ({...val, sort: index + 1}))
    //     this.$emit("input", newData);
    //   }
    // },
    data: {
      handler(val,old) {
        const newData = this.data.map((d, index) => ({...d, sort: index + 1}))
        this.$emit("input", newData);
      },
      immediate: true,
      deep: true,
    },
    value: {
      deep: true,
      immediate: true,
      handler(val) {
        if (val && val.length > 0) {
          let newArr = val.map(data => {
            return {
              ...data,
              initType: 'init',
              sysAttMainVo: {
                sysAttMainIds: data?.sysAttMainVo?.sysAttMainIds || []
              },
              sysAttMainEntities: data.sysAttMainEntities?.map(val => {
                return {
                  ...val, name: val.fileName, url: val.fullFilePath,
                  fullFilePath: val.fullFilePath, id: val.id, filePath: val.filePath
                }
              }),
            }
          })
          // 防止无限循环，简单比较一下
          if (JSON.stringify(val) !== JSON.stringify(this.data)) {
            this.data = newArr
          }
        }
      }
    },
  },
  created() {
    // this.getSysServices();
    this.getDeptTreeSelect()
  },
  methods: {
    createCompanyOptions(value) {
      this.useCompanyOptions.push({
        label: `${value}`,
        value,
      });
    },
    remoteCompanyMethod(search) {
      this.useCompanyLoading = true;
      this.$api.system.dept.selectAllOutDeptList({deptName: search}).then(response => {
        this.useCompanyOptions = response.data.map(val => ({
          ...val,
          label: `${val.deptName}`,
          value: val.deptName,
        }));
        this.useCompanyLoading = false;
      }).catch((e) => {
        this.useCompanyLoading = false;
        this.$message.error(e.toString());
      });
    },
    getDeptTreeSelect() {
      return this.$api.system.dept.treeSelectAllIn().then(response => {
        this.deptMenuOptions = response.data;
      }).catch((e) => {
        this.$message.error(e.toString());
      });
    },
    remoteProject(search,row){
      this.$api.cgzh.getProjectByServiceCode({
        serviceCode:row.serviceCode,
        projectName:search,
      }).then(response => {
        response.data.forEach(val2 => {
          const index = row.projectOptions.findIndex(val => val.businessId === val2.businessId)
          if (index === -1) {
            row.projectOptions.push(val2);
          }
        })
      }).catch((e) => {
        this.$message.error(e.toString());
      });
    },
    onProjectNameChange(val, content, row) {
      if (val) {
        row.projectName = content.option.projectName;
        row.businessIdStatus = 'default';
      } else {
        row.businessIdStatus = 'error';
      }
    },
    onServiceNameChange(val, content, row) {
      if (val) {
        row.serviceName = content.option.serviceName;
        row.serviceCode = content.option.serviceCode;
        row.serviceIdStatus = 'default';
      } else {
        row.serviceIdStatus = 'error';
      }
      row.projectOptions = [];
      // this.$api.cgzh.getProjectByServiceCode(content.option.serviceCode).then(response => {
      //   row.projectOptions = response.data;
      // }).catch((e) => {
      //   this.$message.error(e.toString());
      // });
    },

    getSysServices() {
      this.$api.cgzh.getSysServices().then(response => {
        this.serviceOptions = response.data;
      }).catch((e) => {
        this.$message.error(e.toString());
      });
    },
    checkData() {
      const isValidate = this.data.every((val, index) => {
        if (!val.projectName) {
          this.$set(this.data[index], 'projectNameStatus', 'error')
          this.$message.error(`第${index + 1}条"项目名称"不能为空`);
          return false;
        }
        if (!val.useCompany) {
          this.$set(this.data[index], 'useCompanyStatus', 'error')
          this.$message.error(`第${index + 1}条"应用单位"不能为空`);
          return false;
        }
        this.$set(this.data[index], 'useCompanyStatus', 'default')

        return true;
      });
      return isValidate;
    },
    moveInArray(arr, ffrom, to) {
      // 删除当前的位置
      const item = arr.splice(ffrom, 1);
      // 确保还剩有元素移动
      if (!item.length) {
        this.$message.warning(`There is no item in the array at index ${ffrom}`);
      }
      // 移动元素到指定位置
      arr.splice(to, 0, item[0]);
    },
    addData() {
      this.data.push({
        id: Date.parse(new Date()),
        sysAttMainVo: {
          sysAttMainIds: [],
        },
        // extendId: this.objId,
        serviceId: null,
        serviceName: '',
        serviceCode: '',
        businessId: null,
        projectName: '',
        isInnerProject: '1',
        isInnerCompany: '1',
        useCompany: '',
        useCompanyId: null,
        projectOptions: [],
        efficiency: 0,
        investment: 0
      })
    },
    upData(type) {
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning("请选择一行");
        return;
      }
      if (this.data[0].id === this.selectedRowKeys[0]) {
        this.$message.warning("已是第一行");
      } else {
        const index = this.data.findIndex((val) => val.id === this.selectedRowKeys[0])
        this.moveInArray(this.data, index, index - 1)
      }
    },
    downData(type) {
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning("请选择一行");
        return;
      }
      if (this.data[this.data.length - 1].id === this.selectedRowKeys[0]) {
        this.$message.warning("已是最后一行");
      } else {
        const index = this.data.findIndex((val) => val.id === this.selectedRowKeys[0])
        this.moveInArray(this.data, index, index + 1)
      }
    },
    delData(type) {
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning("请选择一行");
        return;
      }
      const index = this.data.findIndex((val) => val.id === this.selectedRowKeys[0])
      this.data.splice(index, 1);
      this.selectedRowKeys = [];
    },
  }
}
</script>

<style lang="less" scoped>
/deep/ .t-upload__single-display-text{
  justify-content: center;
}
</style>
